package DML;

import java.util.ArrayList;
import java.util.List;

import DuiXiang.TableModel;

public class InsertTableParsing {
	public static int InsertTableParsing(String sql){
		if (sql.charAt(sql.length()-1) != ';')
			return -4;											//语法错误
		int i,j;
		boolean flag = true;
	//	List<String> values = new ArrayList<String>();
		String[] sqlsplit = sql.split("\\s+");
		
		String dataBaseName = sqlsplit[sqlsplit.length - 1].substring(0,
				sqlsplit[sqlsplit.length - 1].length() - 1);
		String tableName = sqlsplit[2];
		String dbfPath = "D:\\database\\" + dataBaseName + "\\" + tableName
				+ ".dbf";
		List<TableModel> tableModelList = util.ReadTableModelList(dbfPath);
		if (tableModelList == null)
			return -1; // 无此表或数据库
		if (!sqlsplit[1].equals("INTO") && !sqlsplit[1].equals("into")) 
			return -4; // 语法错误
		if (!sqlsplit[3].equals("VALUES") && !sqlsplit[3].equals("values"))
			return -4;
		if (!sqlsplit[sqlsplit.length - 2].equals("IN")&& !sqlsplit[sqlsplit.length - 2].equals("in")) 
			return -4;
		sqlsplit[4]=sqlsplit[4].substring(1,sqlsplit[4].length()-1);
		String[] values = sqlsplit[4].split(",");
		String[] fields = new String[values.length];
		for(i=0;i<values.length;i++){
			//System.out.println(values[i]);
			switch(tableModelList.get(i).getsType()){
			case "int":
			case "long":
				for (j = 0; j < values[i].length(); j++)
					if (values[i].charAt(j) < '0'
							|| values[i].charAt(j) > '9')
						break;
				if (j < values[i].length())
					return -3; // 格式不匹配
				break;
			case "float":
				for (j = 0; j < values[i].length(); j++) {
					if (values[i].charAt(j) >= '0'
							&& values[i].charAt(j) <= '9')
						continue;
					else if (values[i].charAt(j) == '.' && flag) {
						flag = false;
						continue;
					} else
						break;
				}
				if (j < values[i].length())
					return -3; // 格式不匹配
				break;
			case "char":
			case "varchar":
				if (values[i].charAt(0) != '\''
						|| values[i].charAt(values[i].length() - 1) != '\''){
					System.out.println("...");
					return -3; // 格式不匹配
					
				}
				else
					values[i] = values[i]
							.substring(1, values[i].length() - 1);
				break;
			default:
				break;
			}
			fields[i]=tableModelList.get(i).getsFieldName();
		}
		int result=InsertTable.InsertIntoTable(dataBaseName, tableName, fields, values);
		
		return result;
	}
}
